package com.lowang.test.springmvc.dao.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import com.lowang.test.springmvc.dao.IUserDao;
import com.lowang.test.springmvc.domain.User;
import com.lowang.test.springmvc.exception.AppException;

@Repository("userDao")
public class UserDaoImpl implements IUserDao {

  @Autowired JdbcTemplate jdbcTemplate;

  @Autowired NamedParameterJdbcTemplate namedParameterJdbcTemplate;

  @Override
  public List<User> list(User user) throws AppException {
    return jdbcTemplate.query(
        "select * from user_info", new BeanPropertyRowMapper<User>(User.class));
  }

  @Override
  public User add(User user) throws AppException {
    KeyHolder holder = new GeneratedKeyHolder();
    namedParameterJdbcTemplate.update(
        "insert into user_info (name,address,age) values(:name,:address,:age)",
        new BeanPropertySqlParameterSource(user),
        holder);
    long id = holder.getKey().longValue();
    user.setId(id);
    int i = 0;
    i = 100 / i;
    return user;
  }

  @Override
  public User delete(Long id) throws AppException {
    long count =
        jdbcTemplate.queryForObject("select count(1) from user_info where id=?", Long.class, id);
    if (count == 0) {
      throw new RuntimeException("用户不存在");
    } else {
      User user =
          jdbcTemplate.queryForObject(
              "select * from user_info where id=?",
              new Object[] {id},
              new BeanPropertyRowMapper<User>(User.class));
      jdbcTemplate.update("delete from user_info where id=?", id);
      return user;
    }
  }

  @Override
  public User update(User user) throws AppException {
    jdbcTemplate.update(
        "update user_info set address=? where id=?", user.getAddress(), user.getId());
    return jdbcTemplate.queryForObject(
        "select * from user_info where id=?",
        new Object[] {user.getId()},
        new BeanPropertyRowMapper<User>(User.class));
  }
}
